package com.alibaba.simpleimage.render;

import java.io.InputStream;

import javax.media.jai.PlanarImage;

import com.alibaba.simpleimage.ImageRender;
import com.alibaba.simpleimage.ImageWrapper;
import com.alibaba.simpleimage.SimpleImageException;
import com.alibaba.simpleimage.render.CropParameter;
import com.alibaba.simpleimage.render.ReadRender;

public class CropRender extends ImageRender {

    protected ImageWrapper image;

    public CropRender(ImageRender imageRender){
        super(imageRender);
    }

    private CropParameter cropParameter = null;

    public CropRender(ImageRender imageRender, CropParameter param){
        super(imageRender);
        this.cropParameter = param;
    }

    public CropRender(InputStream input, CropParameter param){
        super(new ReadRender(input));
        this.cropParameter = param;
    }

    public CropRender(ImageWrapper image, CropParameter param){
        super(null);
        this.image = image;
        this.cropParameter = param;
    }

    @Override
    public void dispose() throws SimpleImageException {
        super.dispose();
        cropParameter = null;
    }

    @Override
    public ImageWrapper render() throws SimpleImageException {
        if (cropParameter == null) {
            return imageRender.render();
        }
        if (image == null) {
            image = imageRender.render();
        }
        for (int i = 0; i < image.getNumOfImages(); i++) {
            PlanarImage pi = ImageCropHelper.crop(image.getAsPlanarImage(i), this.cropParameter);
            image.setImage(i, pi);
        }
        return image;
    }

    public CropParameter getCropParameter() {
        return cropParameter;
    }

    public void setCropParameter(CropParameter cropParameter) {
        this.cropParameter = cropParameter;
    }

}
